package chz.emarket.web.controller;

import java.util.HashMap;
import java.util.List;

import javax.security.auth.login.LoginContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import chz.emarket.exception.WebException;
import chz.emarket.model.Person;
import chz.emarket.service.PersonService;

@Controller
public class UserController {
	
	@Autowired
	private PersonService personService;
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws WebException {
		//Person user = personService.getPersonById(1);
		
		//model.addAttribute("user", user);
		return "login";
	}
	
	@RequestMapping(value="/logout", method=RequestMethod.GET)
	public String loginout(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws WebException {
		HttpSession session = request.getSession();
		session.invalidate();
		return "redirect:/login";
	}
	
	@RequestMapping("/api/login")
	@ResponseBody
	public String doLogin(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws WebException, JsonProcessingException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		
		HttpSession session = request.getSession();
		
		HashMap<String, String> result = new HashMap<>();
		Person user = personService.getPsersonByUserNameAndPassword(userName, password);
		if(null != user) {
			result.put("code", "200");
			result.put("message", "login success");
			result.put("result", "true");
			session.setAttribute("user", user);
		} else {
			result.put("code", "1");
			result.put("message", "login faile");
			result.put("result", "false");
		}
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(result);
	}
	
	@RequestMapping("/user/list")
	public String getUserList(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		List<Person> userList = personService.getUserList();
		System.out.println(userList.size());
		model.addAttribute("userList", userList);
		return "userList";
	}

}
